
if ( typeof Skt.Toolbars === 'undefined' )
	Skt.Toolbars = {};

Skt.Toolbars.setup = function(sketchpad) {
	sketchpad.on("editorToolChanged", Skt.Toolbars.handleToolChange, Skt.Toolbars);
	sketchpad.on("editingEnabledChanged", Skt.Toolbars.handleEditingAvailability, Skt.Toolbars);
	sketchpad.on("groupUpdate", Skt.Toolbars.handleEditingAvailability, Skt.Toolbars);
	sketchpad.on("roomModeratorUpdate", Skt.Toolbars.handleEditingAvailability, Skt.Toolbars);
	sketchpad.on("editorCurrentCanvasChanged", Skt.Toolbars.handleEditingAvailability, Skt.Toolbars);
	sketchpad.on("editorCanvasChanged", Skt.Toolbars.handleEditingAvailability, Skt.Toolbars);
	
	Skt.Toolbars.setupColorpicker();
	Skt.Toolbars.bindToolbarButtons();
	
	Skt.Toolbars.updateActiveToolIcon(sketchpad);
	Skt.Toolbars.updateEditingToolsEnabled(sketchpad.getEditor());
	Skt.Toolbars.setupDisabledActions(sketchpad);
	
	$("#floating-toolbar").draggable({containment: "parent"});
};

Skt.Toolbars.handleEditingAvailability = function(params) {
	setTimeout(function(){
		Skt.Toolbars.updateEditingToolsEnabled(Skt.sketchpad.getEditor()); 
	}, 100);
};

Skt.Toolbars.handleToolChange = function(params) {
	Skt.Toolbars.updateActiveToolIcon(params.editor.getSketchpad());
};

Skt.Toolbars.updateEditingToolsEnabled = function(editor) {
	$(".skt-tool-btn").removeClass('tool-disabled');
	var canvas = editor.getCurrentCanvas();
	var user = editor.getSketchpad().getUser();
	
	if ( canvas != null ) {
		var room = canvas.getRoom();
		if ( !room.getRoomModerator().canEdit(user) ) {
			$('#tool-pen').addClass('tool-disabled');
			$('#tool-clear').addClass('tool-disabled');
			$('#tool-text').addClass('tool-disabled');
			$('#tool-paste').addClass('tool-disabled');
			$('#tool-undo').addClass('tool-disabled');
			$('#tool-redo').addClass('tool-disabled');
			$('#tool-color').addClass('tool-disabled');
			$('#tool-erase').addClass('tool-disabled');
			$("#tool-import").addClass('tool-disabled');
		}
		
		if ( !editor.undoAvailable() )
			$('#tool-undo').addClass('tool-disabled');
		
		if ( !editor.redoAvailable() )
			$('#tool-redo').addClass('tool-disabled');
		
//		if ( !editor.canCopy() )
//			$('#tool-copy').addClass('tool-disabled');
//		
//		if ( !editor.canPaste() )
//			$('#tool-paste').addClass('tool-disabled');
	} 
};

Skt.Toolbars.updateActiveToolIcon = function(sketchpad) {
	var toolName = sketchpad.getEditor().getTool().getName();
	$("#floating-toolbar").find('.skt-tool-btn').removeClass('btn-selected');
	$("#active-tool-icon")
		.removeClass()
		.addClass("skt-icon");
	
	if ( toolName != 'null' ) {
		$("#active-tool-icon").addClass("skt-icon-" + toolName);
		$("#tool-" + toolName).addClass("btn-selected");
	}
};

Skt.Toolbars.setupDisabledActions = function(sketchpad) {
	var user = sketchpad.getUser();
	if ( user.type == Skt.UserType.STUDENT ) {
		$("#add-work-group-btn-toolbar").hide();
		$("#screen-slides-body .btn-toolbar").hide();
	}
};

Skt.Toolbars.setupColorpicker = function() {
	$('#tool-colorpicker').simpleColor({
		cellWidth : 40,
		cellHeight : 40,
		columns : 4,
		border : '1px solid #333333',
		buttonClass : 'button',
		boxWidth : "30px",
		boxHeight : "30px",
		parent : "tool-color",
		colors : [ "111111", "A40000", "5C3566", "204A87", "555753",
				"CC0000", "75507B", "3465A4", "4E9A06", "8F5902",
				"CE5C00", "C4A000", "73D216", "C17D11", "F57900",
				"EDD400" ],
		callback : function(color) {
			Skt.sketchpad.getEditor().setToolOptions({ color: color });
		}
	});

	$('.simpleColorDisplay').html('&#9632;');
	$('.simpleColorDisplay').css('font-size','42px');
	$('.simpleColorDisplay').css('position','relative');
	$('.simpleColorDisplay').css('top','-6px');
	$('.tools .btn .simpleColorContainer').css("height","100%");
	$('.tools .btn .simpleColorContainer').css("width","100%");
	$('.simpleColorContainer .simpleColorDisplay').css("height","100%");
	$('.simpleColorContainer .simpleColorDisplay').css("width","100%");
};


Skt.Toolbars.saveCanvas = function(canvas) {
	var image_b64 = canvas.toDataURL("image/png").replace("data:image/png;base64,", "");
	var image_data = $.base64.atob(image_b64, false);
	
	// Use typed arrays to convert the binary data to a Blob
	var arraybuffer = new ArrayBuffer(image_data.length);
	var view = new Uint8Array(arraybuffer);
	for (var i = 0; i < image_data.length; i++) 
		view[i] = image_data.charCodeAt(i) & 0xff;
	
	var blob = null;
	try {
		// This is the recommended method:
		blob = new Blob([ arraybuffer ], {
			type : 'application/octet-stream'
		});
	} catch (e) {
		console.log("catch!");
		var bb = new (window.WebKitBlobBuilder || window.MozBlobBuilder);
		bb.append(arraybuffer);
		blob = bb.getBlob('application/octet-stream');
	}
	// Use the URL object to create a temporary URL
	var date = new Date();
	var date_txt = $.datepicker.formatDate('dd.M.yy', date);
	var time_txt = date.getHours() + "." + date.getMinutes() + "." + date.getSeconds();
	saveAs(blob, "Slide_" + date_txt + "_" + time_txt + ".png");
};

Skt.Toolbars.bindToolbarButtons = function() {
	
	$("#tool-select").click(function() {
		var editor = Skt.sketchpad.getEditor();
		var selectTool =  new Skt.SelectTool(editor);
		editor.setTool(selectTool);
	});
	
	$("#tool-pen").click(function() {
		var editor = Skt.sketchpad.getEditor(); 
		if (editor.isEditingEnabled()) 
			editor.setTool(new Skt.PenTool(editor));
	});

	$("#tool-erase").click(function() {
		var editor = Skt.sketchpad.getEditor(); 
		if (editor.isEditingEnabled()) 
			editor.removeSelectedElements();
	});
	
	$("#tool-text").click(function() {
		var editor = Skt.sketchpad.getEditor();
		if (editor.isEditingEnabled())
			editor.setTool(new Skt.TextTool(editor));
	});
	
	$('#tool-copy').click(function() {
		var editor = Skt.sketchpad.getEditor();
		if (editor.canCopy())
			editor.copy();
	});
	
	$('#tool-paste').click(function() {
		var editor = Skt.sketchpad.getEditor();
		if (editor.isEditingEnabled() && editor.canPaste())
			editor.paste();
	});
	
	$('#tool-undo').click(function() {
		var editor = Skt.sketchpad.getEditor();
		if (editor.isEditingEnabled() && editor.undoAvailable())
			editor.undo();
	});
	
	$('#tool-redo').click(function() {
		var editor = Skt.sketchpad.getEditor();
		if (editor.isEditingEnabled() && editor.redoAvailable())
			editor.redo();
	});
	
	$('#tool-zoom-in').click(function() {
		var editor = Skt.sketchpad.getEditor();
		var canvas = editor.getCurrentCanvas();
		if ( canvas != null )
			canvas.zoomIn();
		editor.setTool(new Skt.PanTool(editor));
	});
	
	$('#tool-zoom-out').click(function() {
		var editor = Skt.sketchpad.getEditor();
		var canvas = editor.getCurrentCanvas();
		if ( canvas != null )
			canvas.zoomOut();
		editor.setTool(new Skt.PanTool(editor));
	});
	
	$('#tool-pan').click(function() {
		var editor = Skt.sketchpad.getEditor();
		editor.setTool(new Skt.PanTool(editor));
	});
	
	$('#tool-clear').click(function() {
		var user = Skt.sketchpad.getUser(); 
		var editor = Skt.sketchpad.getEditor();
		var canvas = editor.getCurrentCanvas(); 
		
		if ( canvas != null 
				&& editor.isEditingEnabled() 
				&& canvas.getRoom().getRoomModerator().canEdit(user) ) {
			$("<p>Do you wish to delete this slide?</p>").dialog({
				resizable : false,
				title : "Confirmation",
				modal : true,
				buttons : {
					"Yes" : function() {
						Skt.sketchpad.removeRoom(canvas.getRoom().getId(), user);
						$(this).dialog("close");
					},
					"Cancel" : function() {
						$(this).dialog("close");
					}
				}
			});
		}
	});
	
	$("#tool-export").click(function() {
		if ( Skt.sketchpad.getEditor().getCurrentCanvas() != null ) {
			// the canvas calls to output a png
			canvg('canvas', $("#editor").html());
			var canvas = document.getElementById("canvas");
			Skt.Toolbars.saveCanvas(canvas);
		}
	});
	
	$("#tool-import").click(function() {

		var currentRoom = Skt.sketchpad.getCurrentRoom();
		var editor = Skt.sketchpad.getEditor();
		
		if ( currentRoom != null 
				&& editor.isEditingEnabled()
				&& currentRoom.getRoomModerator().canEdit(Skt.sketchpad.getUser()) ) {
		
			var html = '<form action="' + Skt.sketchpad.getBasePath() + '/upload" id="file-upload-form" method="POST" enctype="multipart/form-data" target="upload-files-iframe">';
			html += '<input type="file" id="file" name="file" accept="image/jpeg,image/gif,image/png"/>';
			html +='</form>';
			
			var $msg = $(html);
			
		    BootstrapDialog.show({
		        title: 'Select an image file to upload',
		        message: $msg,
		        buttons: [{
		            label: 'Ok',
		            action: function(dialogRef) {
		            	var file = $("#file").val();
		            	if ( file != null && file != "" ) {
		            		$('#file-upload-form').submit();
		                    dialogRef.close();
		            	} else {
		            		dialogRef.setType(BootstrapDialog.TYPE_DANGER);
		            	}
		            }
		        }, {
		            label: 'Cancel',
		            action: function(dialogRef) {
		            	$("#file").val("");
		                dialogRef.close();
		            }
		        }]
		    });
		    
		}
	});
		
	
};

